import 'package:flutter/material.dart';
import 'package:x3_component_core/components/button_components/base_expand_down_button.dart';

/// 下拉展开列表
class BaseExpandDown extends StatefulWidget {
  final Widget header;
  final Widget collapsed;
  final Widget expanded;
  final BaseExpandDownController controller;
  const BaseExpandDown({Key key, this.header, this.expanded, this.collapsed, this.controller}) : super(key: key);
  @override
  _BaseExpandDownState createState() => _BaseExpandDownState();
}

class _BaseExpandDownState extends State<BaseExpandDown> {
  BaseExpandDownController _controller;
  @override
  void initState() {
    _controller = widget.controller ?? BaseExpandDownController(expanded: false);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
      valueListenable: _controller,
      builder: (BuildContext context, bool value, Widget child) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            widget.header ?? SizedBox(),
            _buildExpandedBody(value),
            BaseExpandDownButton(
              isExpanded: value,
              onPressed: (bool state) {
                _controller.toggle();
              },
            ),
          ],
        );
      },
    );
  }

  Widget _buildExpandedBody(bool value) {
    return AnimatedCrossFade(
      firstChild: widget.collapsed ?? Container(),
      secondChild: widget.expanded ?? Container(),
      firstCurve: Interval(0, 1, curve: Curves.linear),
      secondCurve: Interval(0, 1, curve: Curves.linear),
      sizeCurve: Curves.fastOutSlowIn,
      crossFadeState: value ? CrossFadeState.showSecond : CrossFadeState.showFirst,
      duration: Duration(milliseconds: 300),
    );
  }
}

/// 展开列表控制器
class BaseExpandDownController extends ValueNotifier<bool> {
  BaseExpandDownController({bool expanded = false})
      : assert(expanded != null),
        super(expanded);

  bool get expanded => value;

  set expanded(bool exp) {
    value = exp;
  }

  void toggle() {
    expanded = !expanded;
  }
}
